package com.app.couponsharelife.ui.main.home.group

import android.content.Intent
import androidx.lifecycle.ViewModelProviders
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.lcodecore.tkrefreshlayout.footer.LoadingView
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.PageTipBean
import com.app.couponsharelife.data.bean.TaobaoGoodBean
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.HomeTypeGoodAdapter
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.home.good.GoodDetailActivity
import com.app.couponsharelife.ui.viewmodel.HomeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import kotlinx.android.synthetic.main.activity_group_good.*
import kotlinx.android.synthetic.main.common_tool_bar_layout.*
import java.util.*

class GroupGoodActivity : BaseActivity() {

    /**
     * 标记下拉刷新还是上拉加载
     */
    private var isRefresh = true

    /**
     * 页码
     */
    private var page = 1

    private var mViewModel: HomeViewModel? = null

    override val viewLayoutId: Int get() = R.layout.activity_group_good

    override fun initViews() {
        initToolBar()
        initRecyclerView()
        initRefreshLayout()
    }

    private fun initToolBar() {
        ivBack.setOnClickListener { finish() }
        tvToolBarTitle.text = "淘宝"
    }

    private fun initRecyclerView() {
        mRecyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
        mRecyclerView.adapter = HomeTypeGoodAdapter(arrayListOf(PageTipBean("", 0, 0)), object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                val intent = Intent(this@GroupGoodActivity, GoodDetailActivity::class.java)
                intent.putExtra("good", arg2 as TaobaoGoodBean)
                startActivity(intent)
            }
        })
    }

    private fun initRefreshLayout() {
        mRefreshLayout.setFloatRefresh(true)
        mRefreshLayout.setAutoLoadMore(true)
        mRefreshLayout.setEnableLoadmore(true)
        mRefreshLayout.setEnableOverScroll(false)
        val header = ProgressLayout(this)
        header.setColorSchemeResources(R.color.act_main_bot_nav_select_text_color)
        mRefreshLayout.setHeaderView(header)
        mRefreshLayout.setBottomView(LoadingView(this))
        mRefreshLayout.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                isRefresh = false
                loadData()
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                isRefresh = true
                page = 1
                loadData()
            }
        })
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)
        if (!mViewModel!!.getTaobaoTablePage()!!.hasObservers()) {
            mViewModel!!.getTaobaoTablePage()!!.observe(this, androidx.lifecycle.Observer {
                if (it == null) {
                    handleError("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        mViewModel!!.freshGetTaobaoTablePage(hashMapOf(), false)
                        if (it.error!!.message == "调用出错，请重新尝试")
                            handleError(if (page == 1) "暂无相关商品" else "暂无更多商品")
                        else
                            handleError(parseErrorDate(it.error.message).tip)
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.freshGetTaobaoTablePage(hashMapOf(), false)
                        handleError(if (page == 1) "暂无相关商品" else "暂无更多商品")
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshGetTaobaoTablePage(hashMapOf(), false)
                        handleGoodsContent(it.data!!.data!!.recordss)
                    }
                }
            })
        }
        loadData()
    }

    private fun handleGoodsContent(list: List<TaobaoGoodBean>) {
        if (page == 1 && isRefresh) mRefreshLayout.finishRefreshing() else mRefreshLayout.finishLoadmore()
        if (list.isNotEmpty()) {
            page++
            (mRecyclerView.adapter as HomeTypeGoodAdapter).addData(list, page)
            if (page == 2)
                mRecyclerView.scrollToPosition(0)
        } else {
            handleError(if (page == 1) "暂无相关商品" else "暂无更多商品")
        }
    }

    private fun handleError(msg: String) {
        if (page == 1) mRefreshLayout.finishRefreshing() else mRefreshLayout.finishLoadmore()
        if ((mRecyclerView.adapter as HomeTypeGoodAdapter).list[0] is PageTipBean) {
            ((mRecyclerView.adapter as HomeTypeGoodAdapter).list[0] as PageTipBean).status = 1
            ((mRecyclerView.adapter as HomeTypeGoodAdapter).list[0] as PageTipBean).tip = msg
            ((mRecyclerView.adapter as HomeTypeGoodAdapter).list[0] as PageTipBean).src = R.drawable.ic_data_empty
            (mRecyclerView.adapter as HomeTypeGoodAdapter).notifyItemChanged(0)
        } else showToastMsg(msg)
    }

    private fun loadData() {
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["pageNo"] = page.toString()
        mViewModel?.freshGetTaobaoTablePage(map, true)
    }
}
